package reduce.fz.com.reduce.util;

import android.content.Context;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.TextAppearanceSpan;
import android.widget.TextView;

import reduce.fz.com.reduce.R;
import reduce.fz.com.reduce.bean.User;
import reduce.fz.com.reduce.bean.style.TextSpan;

/**
 * Created by qingshengzheng on 15/9/13.
 */
public class TextSpanUtil {
    public static void setMeKeppingStyle(Context context, TextView textView, String text) {
        text = "您已坚持32天";
        SpannableString styledText = new SpannableString(text);
        styledText.setSpan(new TextAppearanceSpan(context, R.style.my_team_blue_big_text_style), 0, 3, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        styledText.setSpan(new TextAppearanceSpan(context, R.style.my_team_blue_big_text_style), 3, 4, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        textView.setText(styledText, TextView.BufferType.SPANNABLE);
    }

    public static void set(Context context, TextView textView, String desc, int defaultStyle, TextSpan... spans) {
        String result = desc;
        int start = 0;
        int end = 0;
        int b_start = 0;
        for (int i = 0; i < spans.length; i++) {
            TextSpan span = spans[i];
            //处理每个span的开始和结束位置
            String pattern = "{" + i + "}";
            String value = span.text;
            start = desc.indexOf(pattern);
            end = start+span.text.length();
            span.start = start;
            span.end = end;
            result = result.replace(pattern, value);
        }
        //生成Text样式
        int defalut_start = 0;
        int lastend = 0;
        SpannableString styledText = new SpannableString(result);
        for (int i = 0; i < spans.length; i++) {
            TextSpan span = spans[i];
            styledText.setSpan(new TextAppearanceSpan(context, span.style), span.start, span.end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            //设置默认
            if (span.start > defalut_start) {
                styledText.setSpan(new TextAppearanceSpan(context, defaultStyle), defalut_start, span.start, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
            defalut_start = span.end;
        }
        if (result.length() > defalut_start)
            styledText.setSpan(new TextAppearanceSpan(context, defaultStyle), defalut_start, result.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        textView.setText(styledText, TextView.BufferType.SPANNABLE);

    }


}
